﻿using CommandLine;
using CommandLine.Text;
using System;
using System.Collections.Generic;
using System.IO;

namespace OfficeConvert
{
    [Verb("Convert", true, HelpText = "转换office文档")]
    class OfficeVonvertOptions
    {
        /// <summary>
        /// 源文件名称、相对地址、绝对地址
        /// </summary>
        [Option('s', HelpText = "源文件名称、相对地址、绝对地址", Required = true)]
        public string SourceFileName { get; set; }
        /// <summary>
        /// 目标文件相对路径、绝对路径
        /// </summary>
        [Option("td", HelpText = "目标文件相对路径、绝对路径", Required = false)]
        public string TargetDirectory { get; set; }
        /// <summary>
        /// 目标件名称
        /// </summary>
        [Option("tn", HelpText = "目标件名称", Required = true)]
        public string TargetFileName { get; set; }

        [Usage(ApplicationAlias = "OfficeConvert")]
        public static IEnumerable<Example> Examples
        {
            get
            {
                yield return new Example("源文件名称", new OfficeVonvertOptions { SourceFileName = "file.docx", TargetFileName = "file.pdf" });
                yield return new Example("源文件相对地址", new OfficeVonvertOptions { SourceFileName = "Temp/file.docx", TargetFileName = "file.pdf" });
                yield return new Example("源文件相对地址，目标文件相对地址", new OfficeVonvertOptions { SourceFileName = "Temp/file.docx", TargetDirectory = "Temp", TargetFileName = "file.pdf" });
                yield return new Example("源文件绝对地址，目标文件绝对地址", new OfficeVonvertOptions { SourceFileName = "C:/Temp/file.docx", TargetDirectory = "C:/Temp", TargetFileName = "file.pdf" });
            }
        }

        public void Execute()
        {
            var sourceFileInfo = new FileInfo(SourceFileName);
            var targetFileInfo = new FileInfo(Path.Combine(TargetDirectory ?? string.Empty, TargetFileName));

            if (!sourceFileInfo.Exists)
                throw new Exception("源文件不存在！");
            if (!targetFileInfo.Directory.Exists)
            {
                targetFileInfo.Directory.Create();
            }

            if (Core.OfficeConvertFactory.GetConvert(sourceFileInfo.FullName).Convert(sourceFileInfo.FullName, targetFileInfo.FullName))
                Console.WriteLine($"转换成功！文件地址：{targetFileInfo.FullName}");
            else
                Console.WriteLine("转换失败！");
        }
    }
}
